package com.ytkj.digitalConstruction.controller.role;

import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.ytkj.digitalConstruction.ReturnCode;
import com.ytkj.digitalConstruction.entity.role.Role;
import com.ytkj.digitalConstruction.httpbean.role.reqbean.SaveRolePermission;
import com.ytkj.digitalConstruction.httpbean.role.resbean.ReturnFlowPermission;
import com.ytkj.digitalConstruction.httpbean.role.resbean.ReturnMenuPermission;
import com.ytkj.digitalConstruction.httpbean.role.resbean.ReturnPermission;
import com.ytkj.digitalConstruction.service.role.RoleService;
import com.ytkj.digitalConstruction.util.WebTokenUtil;

/**
 * 角色请求入口
 * 
 * @author Pete
 * @Date 2017年12月7日
 */
@RestController
@RequestMapping("/roles")
public class RoleController {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private RoleService roleService;

	/**
	 * 添加角色
	 * 
	 * @author 张重阳
	 * @return
	 */
	@PostMapping("/add")
	public ReturnCode add(@RequestBody @Valid Role req, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		// 判断角色名称是否已存在
		if(roleService.isHasRoleName(req.getRoleId(), req.getRoleName())) {
			return new ReturnCode.Builder().Success(false).Msg("角色名已存在!").build();
		}
		// 添加角色
		Integer rows = roleService.add(req);
		if (rows == null || rows == 0) {
			log.error("添加角色失败:" + req.toString());
			return new ReturnCode.Builder().Success(false).Msg("添加角色失败！").build();
		}
		log.info("添加角色成功:" + req.toString());
		return new ReturnCode.Builder().Success(true).Msg("添加角色成功！").Object(req).build();
	}

	/**
	 * 修改角色
	 * 
	 * @author 张重阳
	 * @return
	 */
	@PostMapping("/update")
	public ReturnCode update(@RequestBody Role role, BindingResult bindingResult) {
		// 判断参数是否合法
		if (bindingResult.hasErrors()) {
			String msg = bindingResult.getFieldError().getDefaultMessage();
			return new ReturnCode.Builder().Success(false).Msg(msg).build();
		}
		if (role.getRoleId() == null) {
			return new ReturnCode.Builder().Success(false).Msg("角色ID不能为空！").build();
		}
		// 判断角色名称是否已存在
		if (roleService.isHasRoleName(role.getRoleId(), role.getRoleName())) {
			return new ReturnCode.Builder().Success(false).Msg("角色名称已存在！").build();
		}
		// 修改角色
		Integer rows = roleService.update(role);
		if (rows == null || rows == 0) {
			log.error("修改角色失败:" + role.toString());
			return new ReturnCode.Builder().Success(false).Msg("修改角色失败！").build();
		}
		log.info("修改角色成功:" + role.toString());
		return new ReturnCode.Builder().Success(true).Msg("修改角色成功！").Object(role).build();
	}

	/**
	 * 查询角色列表
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/list")
	public ReturnCode list() {
		List<Role> roleList = roleService.selectAll();
		log.info("角色列表获取成功:" + JSONArray.toJSONString(roleList));
		return new ReturnCode.Builder().Success(true).Msg("角色列表获取成功！").Object(roleList).build();
	}

	/**
	 * 删除角色
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/delete/{id}")
	public ReturnCode delete(@PathVariable Integer id) {
		if (id == null) {
			return new ReturnCode.Builder().Success(false).Msg("角色ID不能为空！").build();
		}
		Integer rows = roleService.delete(id);
		if (rows == 1) {
			log.error("有用户含有该角色，删除角色失败：" + id);
			return new ReturnCode.Builder().Success(false).Msg("有用户含有该角色，删除角色失败！").Object(id).build();
		}
		if (rows == 2) {
			log.error("有用户组含有该角色，删除角色失败：" + id);
			return new ReturnCode.Builder().Success(false).Msg("有用户组含有该角色，删除角色失败！").Object(id).build();
		}
		if (rows == -1) {
			log.error("数据层执行删除该角色，删除角色失败：" + id);
			return new ReturnCode.Builder().Success(false).Msg("数据层执行删除该角色，删除角色失败！").Object(id).build();
		}
		log.info("删除角色成功：" + id);
		return new ReturnCode.Builder().Success(true).Msg("删除角色成功！").Object(id).build();
	}

	/**
	 * 获取树形角色权限
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/getPermissionTree/{id}")
	public ReturnCode getPermissionTree(@PathVariable Integer id) {
		if (id == null) {
			return new ReturnCode.Builder().Success(false).Msg("角色ID不能为空！").build();
		}
		ReturnPermission returnPermission = new ReturnPermission();
		// 获取菜单权限
		List<ReturnMenuPermission> menuPermissionList = roleService.getMenuPermissionList(id);
		returnPermission.setMenuPermissionList(menuPermissionList);
		// 获取流程权限
		List<ReturnFlowPermission> flowPermissionList = roleService.getFlowPermissionList(id);
		returnPermission.setFlowPermissionList(flowPermissionList);
		log.info("获取角色权限成功：" + id);
		return new ReturnCode.Builder().Success(true).Msg("获取角色权限成功！").Object(returnPermission).build();
	}

	/**
	 * 获取树形角色权限
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/getAllPermission")
	public ReturnCode getAllPermission() {
		ReturnPermission returnPermission = new ReturnPermission();
		// 获取菜单权限
		List<ReturnMenuPermission> menuPermissionList = roleService.getTreeMenuPermission();
		returnPermission.setMenuPermissionList(menuPermissionList);
		// 获取流程权限
		List<ReturnFlowPermission> flowPermissionList = roleService.getTreeFlowPermission();
		returnPermission.setFlowPermissionList(flowPermissionList);
		log.info("获取权限树成功");
		return new ReturnCode.Builder().Success(true).Msg("获取权限树成功！").Object(returnPermission).build();
	}

	/**
	 * 获取角色权限列表
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/getPermissionList/{id}")
	public ReturnCode getPermissionList(@PathVariable Integer id) {
		List<Integer> roleList = roleService.selectPermissionIdByRoleId(id);
		log.info("获取角色权限成功：" + JSONArray.toJSONString(roleList));
		return new ReturnCode.Builder().Success(true).Msg("获取角色权限成功！").Object(roleList).build();
	}

	/**
	 * 获取角色权限
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/role")
	public ReturnCode role(HttpServletRequest request) {
		// 从request中获取用户Id
		Integer userId = WebTokenUtil.getUserId(request);
		ReturnPermission returnPermission = new ReturnPermission();
		// 获取菜单权限
		List<ReturnMenuPermission> menuPermissionList = roleService.getMenuPermissionListByUserId(userId);
		returnPermission.setMenuPermissionList(menuPermissionList);
		// 获取流程权限
		List<ReturnFlowPermission> flowPermissionList = roleService.getFlowPermissionListByUserId(userId);
		returnPermission.setFlowPermissionList(flowPermissionList);
		log.info("获取用户权限成功：" + userId);
		return new ReturnCode.Builder().Success(true).Msg("获取角色权限成功！").Object(returnPermission).build();
	}

	/**
	 * 获取角色权限
	 * 
	 * @author 张重阳
	 * @return
	 */
	@GetMapping("/permissionList")
	public ReturnCode permissionList(HttpServletRequest request) {
		// 从request中获取用户Id
		Integer userId = WebTokenUtil.getUserId(request);
		Set<Integer> permissionList = roleService.getPermissionListByUserId(userId);
		return new ReturnCode.Builder().Success(true).Msg("获取角色权限成功！").Object(permissionList).build();
	}

	/**
	 * 保存角色权限
	 * 
	 * @return
	 */
	@PostMapping("/save")
	public ReturnCode saveRolePermission(@RequestBody @Valid SaveRolePermission saveRolePermission) {
		// 删除角色所有权限
		roleService.deletePermission(saveRolePermission.getRoleId());
		// 给角色添加权限
		roleService.insert(saveRolePermission);
		return new ReturnCode.Builder().Success(true).Msg("角色权限保存成功").build();
	}
}
